<?php


namespace App\Command\Model;

use App\Service\Sms as SmsService;
use App\Service\Mailer as MailerService;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Validation;
use PHPMailer\PHPMailer\Exception;

class Interview {

    /**
     * 发送通知
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws Exception
     */
    public function sendNotice() {
        $sql = 'SELECT id,batchcode,creator,createdate,updatedate,sendtype,templatetype,status,senddate,totalcount,sendbysys,jobname,jobcompany,interviewtime,address,contract,mobilephone,memo,creatorname FROM Interview WHERE senddate>=date_sub(now(), interval 1 day) and senddate<Now() and status=? ORDER BY id';
        $var = ['00'];

        $interviewInfo = Db::selectOne($sql, $var);
        if (empty($interviewInfo)) {
            return null;
        }
        $updSql = 'UPDATE Interview SET status=?,updatedate=Now() WHERE id=?';
        $updVar = ['01', $interviewInfo['id']];
        Db::update($updSql, $updVar);

        $sql = 'SELECT id,email,mobilephone,name FROM InterviewDetail WHERE batchcode=?';
        $var = [$interviewInfo['batchcode']];
        $resumeList = Db::select($sql, $var);

        $smsContent = $emailContent = $subject = '';
        if ($interviewInfo['sendtype'] == 1 || $interviewInfo['sendtype'] == 3) {
            $interviewTime = date('n月j日G时i分', strtotime($interviewInfo['interviewtime']));
            switch ($interviewInfo['templatetype']) {
                case '1':
                    //面试邀约
                    $smsContent = "##name##您好，诚邀您参加" . $interviewInfo['jobcompany'] . "的" . $interviewInfo['jobname'] . "职位的面试\r\n" .
                        "面试时间：" . $interviewTime . "\r\n" .
                        "面试地址：" . $interviewInfo['address'] . "\r\n" .
                        "联系人：" . $interviewInfo['contract'] . " 手机号：" . $interviewInfo['mobilephone'] . "\r\n" .
                        (empty($interviewInfo['memo']) ? '' : ("注意事项：" . $interviewInfo['memo'] . "\r\n")) .
                        "祝面试顺利。\r\n" .
                        "退订回51";
                    break;
                case '2':
                    $smsContent = "诚邀您参加" . $interviewInfo['jobcompany'] . "的面试\r\n" .
                        "面试时间：" . $interviewTime . "\r\n" .
                        "面试地址：" . $interviewInfo['address'] . "\r\n" .
                        "联系人：" . $interviewInfo['contract'] . " 手机号：" . $interviewInfo['mobilephone'] . "\r\n" .
                        (empty($interviewInfo['memo']) ? '' : ("注意事项：" . $interviewInfo['memo'] . "\r\n")) .
                        "祝面试顺利。\r\n" .
                        "退订回51";
                    break;
                case '3':
                default:
                    $smsContent = "温馨提示：" . $interviewInfo['jobcompany'] . "的面试，还请准时参加\r\n" .
                        "面试时间：" . $interviewTime . "\r\n" .
                        "面试地址：" . $interviewInfo['address'] . "\r\n" .
                        "联系人：" . $interviewInfo['contract'] . " 手机号：" . $interviewInfo['mobilephone'] . "\r\n" .
                        "请您提前安排好时间及乘车路线，以便准时到达面试。\r\n祝面试顺利。\r\n" .
                        "退订回51";
                    break;
            }
        }
        if ($interviewInfo['sendtype'] == 2 || $interviewInfo['sendtype'] == 3) {
            $interviewTimestamp = strtotime($interviewInfo['interviewtime']);
            $weekDay = date('w', $interviewTimestamp);
            $weekName = ['周日', '周一', '周二', '周三', '周四', '周五', '周六',];
            $interViewTime = date('n月j日', $interviewTimestamp) . '(' . $weekName[$weekDay] . ')' . date('G时i分', $interviewTimestamp);
            $interviewInfo['templatetype'] = in_array($interviewInfo['templatetype'], [1, 2, 3]) ? $interviewInfo['templatetype'] : 1;
            $subject = $interviewInfo['jobcompany'] . ($interviewInfo['templatetype'] == 3 ? '-面试提醒' : '-面试邀请函');
            $templateFile = ROOT_PATH . "/Data/Template/interview_" . $interviewInfo['templatetype'] . ".html";
            $emailContent = file_get_contents($templateFile);
            $interviewMemo = (empty($interviewInfo['memo']) ? '' : ("注意事项：" . nl2br($interviewInfo['memo']) . "<br />"));
            $emailContent = str_replace([
                '{{jobCompany}}', '{{jobName}}', '{{interviewTime}}', '{{interviewAddress}}', '{{interviewContact}}', '{{interviewMobilephone}}', '{{interviewMemo}}',
            ], [
                $interviewInfo['jobcompany'], $interviewInfo['jobname'], $interViewTime, $interviewInfo['address'], $interviewInfo['contract'], $interviewInfo['mobilephone'], $interviewMemo
            ], $emailContent);
        }

        $sms = new SmsService();
        $channel = config('app.sms.channel.rpo');
        $mailer = new MailerService();
        $mailer->isJobsmail();
        $mailer->setFrom($mailer->defaultSender['noreplay']['email'], $mailer->defaultSender['noreplay']['name']);
        $mailer->setJobsmailFlag(config('mail.flag.interviewmail', 0));
        $logoPath = ROOT_PATH . "/Data/Image/logo.png";
        $logoCid = '';
        foreach ($resumeList as $item) {
            $updateData = [
                'status' => '02',
                'realsenddate' => date('Y-m-d H:i:s'),
            ];
            if ($interviewInfo['sendtype'] == 1 || $interviewInfo['sendtype'] == 3) {
                //发送短信，验证手机格式
                if (empty($item['mobilephone']) || !Validation::validatePhone('mobilephone', $item['mobilephone'])) {
                    $updateData['smsresult'] = '0';
                    $updateData['smsfailreason'] = '手机号格式不正确';
                } else {
                    $itemContent = str_replace('##name##', $item['name'], $smsContent);
                    if ($sms->send($item['mobilephone'], $itemContent, $channel)) {
                        $updateData['smsresult'] = '1';
                    } else {
                        $updateData['smsresult'] = '0';
                        $updateData['smsfailreason'] = $sms->getMessage();
                    }
                }
            }
            if ($interviewInfo['sendtype'] == 2 || $interviewInfo['sendtype'] == 3) {
                if (empty($logoCid)) {
                    $logoCid = $mailer->getUuid();
                    $mailer->addEmbeddedImage($logoPath, $logoCid, 'logo.png');
                    $emailContent = str_replace('{{logo}}', 'cid:' . $logoCid, $emailContent);
                }
                //发送短信，验证手机格式
                if (empty($item['email']) || !Validation::validateEmail('email', $item['email'])) {
                    $updateData['emailresult'] = '0';
                    $updateData['emailfailreason'] = '邮箱格式不正确';
                } else {
                    $itemContent = str_replace('{{name}}', $item['name'], $emailContent);
                    //发送邮件
                    $mailer->Subject = $subject;
                    $mailer->clearAddresses();
                    $mailer->addAddress($item['email']);
                    $mailer->isHTML(true);
                    $mailer->Body = $itemContent;

                    if ($mailer->send()) {
                        $updateData['emailresult'] = '1';
                    } else {
                        $updateData['emailresult'] = '0';
                        $updateData['emailfailreason'] = $mailer->ErrorInfo;
                    }
                }
            }

            $updResumeSql = 'UPDATE InterviewDetail SET ';
            $updResumeVar = [];
            foreach ($updateData as $fieldName => $fieldValue) {
                $updResumeSql .= $fieldName . '=?,';
                $updResumeVar[] = $fieldValue;
            }
            $updResumeSql .= 'updatedate=Now() WHERE id=?';
            $updResumeVar[] = $item['id'];

            Db::update($updResumeSql, $updResumeVar);
        }
        //更新汇总表为已发送
        $updSql = 'UPDATE Interview SET status=?,updatedate=Now() WHERE id=?';
        $updVar = ['02', $interviewInfo['id']];
        Db::update($updSql, $updVar);

        return count($resumeList);
    }
}